<template>
  <div class="window drag" @dragover="dragover" @dragenter="dragover" @drop="dropFn">
    <Table :columns="columns" :data="tableData" border size="small"></Table>
    <div class="footer">
      <Button type="error" size="small" @click="tableData = []">清空表格</Button>
      <Button type="warning" size="small" @click="startCompression" :disabled="startDisabled">开始压缩</Button>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
// import axios from 'axios'
const axios = require('axios')
const {readdir, readFile, writeFile } = require('node:fs/promises')

const columns = ref([
  {
    title: "id",
    key: "id",
  },
  {
    title: "path",
    key: "path",
  },
  {
    title: "name",
    key: "name",
  },
  {
    title: "oldSize",
    key: "oldSize",
  },
  {
    title: "newSize",
    key: "newSize",
  },
  {
    title: "status",
    key: "status",
  },
])
const tableData = ref([])

function dragover(e) {
  e.stopPropagation()
  e.preventDefault()
}
async function dropFn(e) {
  dragover(e)
  if (e.loading) return
  var files = e.dataTransfer.files
  for (let i = 0; i < files.length; i++) {
    let path = files[i].path.replace(/\\/g, '/')
    if(files[i].type !== '') {
      // 文件
      tableData.value.push({
        id: i,
        path: path,
        name: files[i].name,
        oldSize: files[i].size,
        newSize: '',
        status: '',
      })
      
    } else {
      // 文件夹
      const files2 = await readdir(path)
      for (let j = 0; j < files2.length; j++) {
        let path2 = path + '/' + files2[j]
        if(files2[j].type !== '') {
          tableData.value.push({
            id: j + 1,
            path: path2,
            name: files2[j],
            oldSize: '',
            newSize: '',
            status: '',
          })

        }
      }
    }
    
  }

}
const startDisabled = ref(false)
async function startCompression(){
  if(tableData.value.length === 0) return alert('请先选择文件')

  startDisabled.value = true

  for (let i = 0; i < tableData.value.length; i++) {
    if(!tableData.value[i].isRun) {
      console.log(i)
      await compressionFile(i)
    }
  }

  startDisabled.value = false
  alert('压缩完毕')

}

function compressionFile(i){
  return new Promise(async (resolve, reject)=>{
    try {
      tableData.value[i].isRun = true
      tableData.value[i].status = '正在处理'
      let data = await readFile(tableData.value[i].path)
      let headers = {
        'Origin': 'https://tinypng.com',
        'Referer': 'https://tinypng.com/',
        'Content-Type': 'image/jpeg'
      }
      const {data: res } = await axios.post('https://tinypng.com/web/shrink', data, headers)
      let url = res.output.url
      if(!url) {
        tableData.value[i].status = '处理失败'
        tableData.value[i].isRun = false
         resolve('no')
        return
      }
      let {data: res2} = await axios.get(url, { responseType: 'arraybuffer' })
      res2 = new Uint8Array(res2)
      const res3 = await writeFile(tableData.value[i].path, res2)
      tableData.value[i].newSize = res2.length
      tableData.value[i].isRun = false
      tableData.value[i].status = '压缩完毕'
      resolve('ok')
    } catch (error) {
      tableData.value[i].isRun = false
      console.log('error', error)
      resolve('no')
    }
  })
}


</script>


<style>
html,body{
  width: 100%;
  height: 100%;
}
#app{
  width: 100%;
  height: 100%;
}
.window{
  background-color: #fff;
  width: 100%;
  height: 100%;
}
.ivu-table-tbody .ivu-table-cell{
  padding: 0 5px;
  word-break: normal;
}
.ivu-table-small td{
  height: 30px;
}
.footer{
  display: flex;
  justify-content: flex-end;
  padding: 10px;
}
.ivu-btn{
  margin-right: 10px;
  font-size: 12px;
}
</style>
